#!/bin/sh
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#

#
# Run a simple backup of the Bacula build directory
#   then restore it.
#
TestName="estimate-test"
. scripts/functions
JobName=BackupClient1

scripts/cleanup
scripts/copy-confs

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf

start_test

rm -rf ${cwd}/build/src/test ${cwd}/build/po/test
mkdir -p ${cwd}/build/src/test
touch ${cwd}/build/src/test/test1 ${cwd}/build/src/test/test2

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=1
run job=$JobName yes
wait
messages
@#
@# now do a restore
@#
@$out $tmp/log2.out
restore where=$tmp/bacula-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula

check_two_logs
check_restore_diff

mv ${cwd}/build/src/test ${cwd}/build/po/test

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log3.out
estimate listing job=$JobName level=incremental
messages
quit
END_OF_DATA

run_bconsole

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log4.out
estimate listing job=$JobName level=incremental accurate=yes
messages
quit
END_OF_DATA

run_bconsole

cp $scripts/bacula-dir.conf $tmp/1
sed 's/JobDefs {/JobDefs { Accurate=yes/' $tmp/1>$scripts/bacula-dir.conf

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log5.out
reload
estimate listing job=$JobName level=incremental
messages
quit
END_OF_DATA

run_bconsole

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log6.out
estimate listing job=$JobName level=incremental accurate=no
messages
quit
END_OF_DATA

run_bconsole

rm -rf ${cwd}/build/po/test

grep test1 $tmp/log3.out > /dev/null
if [ $? = 0 ]; then
    print_debug "ERROR: Normal estimate shouldn't detect test1 file in $tmp/log3.out"
    dstat=2
fi

grep test1 $tmp/log4.out > /dev/null
if [ $? != 0 ]; then
    print_debug "ERROR: Accurate=yes estimate should detect test1 file in $tmp/log4.out"
    dstat=2
fi

grep test1 $tmp/log5.out > /dev/null
if [ $? != 0 ]; then
    print_debug "ERROR: Accurate estimate should detect test1 file in $tmp/log5.out"
    dstat=2
fi

grep test1 $tmp/log6.out > /dev/null
if [ $? = 0 ]; then
    print_debug "ERROR: Accurate=no estimate shouldn't detect test1 file in $tmp/log6.out"
    dstat=2
fi

check_for_zombie_jobs storage=File1

stop_bacula
end_test
